package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.service.api.admin.AppIndexGoodsApi;
import com.jmp.service.api.admin.dto.AppIndexGoodsRemoveRequest;
import com.jmp.service.api.admin.dto.AppIndexGoodsRequest;
import com.jmp.service.api.admin.dto.AppIndexGoodsResponse;
import com.jmp.service.api.admin.dto.AppIndexGoodsSaveRequest;
import lombok.extern.slf4j.Slf4j;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.mapper.AppIndexGoodsMapperExt;
import one.stand.model.AppIndexGoods;
import one.stand.model.ResultModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@RestController
@Slf4j
public class AppIndexGoodsController implements AppIndexGoodsApi {
    @Autowired
    private AppIndexGoodsMapperExt appIndexGoodsMapperExt;

    @Override
    public ResultModel<AppIndexGoodsResponse> list(@RequestBody AppIndexGoodsRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<AppIndexGoods> indexGoodsList = appIndexGoodsMapperExt.selectList(request.getType(), request.getRefId(), request.getNameLike());

        PageResponse2<AppIndexGoodsResponse.Goods> goodsList = ConvertUtils.page2(indexGoodsList, goods -> {
            return AppIndexGoodsResponse.Goods.builder()
                    .id(goods.getId())
                    .goodsId(goods.getGoodsId())
                    .sort(goods.getSort())
                    .refId(goods.getRefId())
                    .build();
        });

        AppIndexGoodsResponse response = AppIndexGoodsResponse.builder()
                .goodsList(goodsList)
                .build();
        return ResultModel.success(response);
    }

    @Override
    public ResultModel appIndexGoodsSave(@RequestBody AppIndexGoodsSaveRequest request) {
        AppIndexGoods appIndexGoods = new AppIndexGoods();
        appIndexGoods.setId(request.getId());
        appIndexGoods.setGoodsId(request.getGoodsId());
        appIndexGoods.setSort(request.getSort());
        if (Objects.isNull(appIndexGoods.getId())) {
            appIndexGoods.setType(request.getType());
            appIndexGoods.setRefId(request.getRefId());
            appIndexGoodsMapperExt.insertSelective(appIndexGoods);
        } else {
            appIndexGoodsMapperExt.updateByPrimaryKeySelective(appIndexGoods);
        }
        return ResultModel.success();
    }

    @Override
    public ResultModel appIndexGoodsRemove(@RequestBody AppIndexGoodsRemoveRequest request) {
        appIndexGoodsMapperExt.deleteByPrimaryKey(request.getId());
        return ResultModel.success();
    }
}
